package calao.client.ui;

import calao.client.util.DateRange;
import calao.client.util.DateRange.IndexRange;

import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.Element;

/** Shows events as horizontal bars accross day columns of a sizeable calendar. 
 */ 
public class GanttChart
extends Composite
implements ClickListener
{

	final static String STYLE = "calao-GanttChart";
	
	final static int LINE_HEIGHT = 21;
	
	final FlowPanel panel = new FlowPanel();
	
	final TooltipProvider tooltipProvider = new TooltipProvider() {
		public Widget getTooltip(Widget w) {
			return ((GanttTask)w).getTooltip();
		}
	};

	final DateRange dateRange;
	final TimeTable frame;
	final Element[] bgColumns;
	
	int eventCount = 0;	
	
	public GanttChart(DateRange dateRange)
	{
		this.dateRange = dateRange;
		frame = new TimeTable(dateRange);
		frame.buildHeaders();
		panel.add(frame);
		panel.addStyleName(STYLE);
		initWidget(panel);
		bgColumns = new Element[dateRange.getDayCount()];
		for (int col=0; col<dateRange.getDayCount(); col++) {
			Elements.setHeight(bgColumns[col] = frame.addEmptyCell(), 4);
		}
	}
	
	public void refresh()
	{
		// resize background columns
		for (int col=0; col<dateRange.getDayCount(); col++) {
			Elements.setHeight(bgColumns[col], eventCount*LINE_HEIGHT+4);
		}
	}
	
	public boolean add(GanttTask event)
	{
		IndexRange range = dateRange.getPeriodDays(event.start, event.end);
		if (range==null) return false;
		Element element = event.getElement();
		Elements.setWidth(element, frame.getColSpanWidth(range.length())-5);
		Elements.setTop(element, frame.getContentTop()+2+eventCount*LINE_HEIGHT);
		Elements.setLeft(element, frame.getColumnLeft(range.getStart()));
		eventCount++;
		panel.add(event);
		event.addClickListener(this);
		event.addMouseListener(tooltipProvider);
		return true;
	}
				
	public DateRange getDateRange() 
	{
		return dateRange;
	}

	public void onClick(Widget sender) 
	{
		((GanttTask)sender).onClick();
	}
	
	protected void onLoad()
	{
		tooltipProvider.start();
	}

	protected void onUnload()
	{
		tooltipProvider.stop();
	}

}
